/*
 *  processImage.cpp
 *  Ball and Plate
 *
 *  Created by Kenn Sebesta on 2008-02-29.
 *  Copyright 2007 __MyCompanyName__. All rights reserved.
 *
 */

#include "processImage.h"

extern int viewSize;

void processImage( IplImage *camFrame, ImageSet *images, ImageAnalysisParams *params){
    
    cvSetImageROI( camFrame, images->cropRect );
    
    if(params->isDifferent){
        
        if(params->isDifferent>0){
            cvReleaseImage( &images->cropImage );
            cvReleaseImage( &images->grayImage );
            cvReleaseImage( &images->bwImage );
            cvReleaseImage( &images->edgeImage );
        }
        
        images->cropImage = cvCreateImage(cvSize( viewSize, viewSize ), camFrame->depth, camFrame->nChannels);
        images->grayImage = cvCreateImage(cvGetSize(images->cropImage), images->cropImage->depth, 1);
        images->bwImage = cvCreateImage(cvGetSize(images->cropImage), images->cropImage->depth, 1);
        images->edgeImage = cvCreateImage(cvGetSize(images->cropImage), images->cropImage->depth, 1);
        
        params->isDifferent=0;
    }
    
#if defined DEBUG && (DEBUG > 3)
    printf("Error 12\n");
    printf("images.cropRect = %d, %d\n", images->cropRect.width, images->cropRect.height);
#endif
    if(images->cropRect.width==images->cropImage->width)
        cvCopy( camFrame, images->cropImage );
    else
        cvResize( camFrame, images->cropImage, CV_INTER_AREA  );
    
#if defined DEBUG && (DEBUG > 3)
    printf("Error 13\n");
#endif
    
    if (images->cropImage->nChannels!=1){
        cvSplit( images->cropImage, images->grayImage, NULL, NULL, NULL );
        //	cvCvtColor(cropImage, grayImage, CV_BGR2GRAY);	//Can't figure out how to tell if it's a RGB or
        //grayscale because my camera returns three
        //channels, even though it's grayscale.
    }
    else{
        cvCopy(images->cropImage, images->grayImage);
    }
    
#if defined DEBUG && (DEBUG > 3)
    printf("Error 17\n");
#endif
    
    cvCopy( images->grayImage, images->bwImage );
    cvCanny( images->bwImage, images->edgeImage, params->cannyThreshLow, params->cannyThreshHigh, 3 ); // Performs the edge extraction on the image
    
    return;
}
